<?php

namespace app\api\model\shop;


use app\api\model\Qrcode;
use app\common\model\User;
use app\shopapi\model\ExtendConsumeShop;
use app\shopapi\model\ShopGoods;
use extend\Poster as PosterExtend;
use think\Db;
use think\Model;
use traits\model\SoftDelete;
require_once ROOT_PATH.'extend/Poster.php';

class Shop extends Model
{
    use SoftDelete;

    // 表名
    protected $name = 'shop';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';


    public function Goods()
    {
        return $this->hasMany('\\app\\shopapi\\model\\ShopGoods', 'shop_id', 'shop_id');
    }


    public function hasDuplicates($array1, $array2) {
        $diff = array_diff(array_merge($array1, $array2), array_intersect($array1, $array2));
        return !empty($diff);
    }

    public function getWeek()
    {
        return [1=>'周一',2=>'周二',3=>'周三',4=>'周四',5=>'周五',6=>'周六',0=>'周日'];
    }

    public function getUseDate()
    {
        return [1=>'周一',2=>'周二',3=>'周三',4=>'周四',5=>'周五',6=>'周六',0=>'周日',7=>'节假日通用',8=>'节假日不可用'];
    }

    //转换店铺的营业日期
    public function getWorkWeek($week)
    {
        $week = explode(',',$week);
        $week_list = [0,1,2,3,4,5,6];

        $res = $this->hasDuplicates($week,$week_list);
        $week_list = $this->getWeek();
        if ($res){

            $work_week = [];
            foreach ($week as $k=>$v){
                array_push($work_week,$week_list[$v]);
            }
            return $work_week;
        } else {
            return '周一至周日';
        }
    }

    //转换商品的可用日期
    public function getGoodsUseDate($week)
    {
        $week = explode(',',$week);
        $week_list = [0,1,2,3,4,5,6,7,8];

        $res = $this->hasDuplicates($week,$week_list);
        $week_list = $this->getUseDate();
        if ($res){

            $work_week = [];
            foreach ($week as $k=>$v){
                array_push($work_week,$week_list[$v]);
            }
            return implode(',',$work_week);
        } else {
            return '周一至周日';
        }
    }

    //商品列表
    public function getGoodsList($condition,$limit=null)
    {
        $goods_list = ShopGoods::where($condition)
            ->field('goods_id,line_price,price,goods_name,images,commission_rate')
            ->order('createtime desc')
            ->limit($limit)
            ->select();
        foreach ($goods_list as $k=>$v){
            $goods_list[$k]['rebate'] = $this->goods_rebate($v['price'],$v['commission_rate']);
        }
        return $goods_list;
    }

    public function getShopInfo($condition,$lat='',$lng='')
    {
        $shop_info = Shop::where($condition)
            ->field('shop_id,shop_name,category_id,address,lat,lng,commission_rate,work_week,banner_img,start_time,end_time,mobile,recommend_url')
            ->find();

        if (!empty($lat)&&!empty($lng)){
            $distance = getDistance((float) $shop_info[ 'lng' ], (float) $shop_info[ 'lat' ], (float) $lng, (float) $lat);
            $shop_info['distance'] = $distance/1000;
        } else {
            $shop_info['distance'] = 0;
        }

        $shop_info['work_week'] = $this->getWorkWeek($shop_info['work_week']);
        $shop_info['discount'] = $this->calculate_discount($shop_info['commission_rate']);
        return $shop_info;
    }

    //商品详情
    public function goodsDetail($goods_id,$lat,$lng)
    {
        $goods_info = ShopGoods::where(['goods_id'=>$goods_id])
            ->field('goods_id,shop_id,goods_name,profile,use_people_type,start_use_people,end_use_people,images,sku,detail,
            may_use_time_type,start_may_use_time,end_may_use_time,may_use_time_day,use_time_type,start_use_time,end_use_time,
            price,line_price,other_rule,goods_state,privateroom_type,enjoy_preferential_type,sale,commission_rate,use_date,use_date_type')
            ->find();
        $goods_info['rebate'] = $this->goods_rebate($goods_info['price'],$goods_info['commission_rate']);
        if ($goods_info['use_date_type']==1){
            $goods_info['use_date'] = $this->getGoodsUseDate($goods_info['use_date']);
        } else {
            $goods_info['use_date'] = '所有日期可用';
        }
        $shop_info =  $this->getShopInfo(['shop_id'=>$goods_info['shop_id']],$lat,$lng);
        $data = [
            'goods_info'=>$goods_info,
            'shop_info'=>$shop_info,
        ];

        return $data;
    }

    //订单商品详情
    public function orderGoodsDetail($goods_id)
    {
        $goods_info = ShopGoods::where(['goods_id'=>$goods_id])
            ->field('goods_id,shop_id,goods_name,profile,use_people_type,start_use_people,end_use_people,images,sku,detail,
            may_use_time_type,start_may_use_time,end_may_use_time,may_use_time_day,use_time_type,start_use_time,end_use_time,
            price,line_price,other_rule,goods_state,privateroom_type,enjoy_preferential_type,sale,commission_rate')
            ->find();
        $goods_info['rebate'] = $this->goods_rebate($goods_info['price'],$goods_info['commission_rate']);

        return $goods_info;
    }


    //商户详情
    public function detail($shop_id,$lat,$lng)
    {
        $shop_info =  $this->getShopInfo(['shop_id'=>$shop_id],$lat,$lng);

        $goods_list = $this->getGoodsList(['shop_id'=>$shop_id,'goods_state'=>1]);

        $data = [
            'shop_info'=>$shop_info,
            'goods_list'=>$goods_list
        ];

        return $data;
    }

    //可操作的商品列表
    public function operationLists($params)
    {


    }

    public function recommendShop($params)
    {
        $order = isset($params['order'])?$params['order']:'createtime';

        $sort = isset($params['sort'])?$params['sort']:'desc';

        $keyword = $params['keyword'];

        $where = ['su.recommender_id'=>$params['user_id'],'s.audit_status'=>3];

        if(!empty($keyword)){
            $where['s.shop_name'] = ['like',"%$keyword%"];
        }

        //$order = 's.createtime desc';
        // 非法参数进行过滤
        /*if ($order != '') {
            if ($order != "sale_num" && $order != "discount_price") {
                $order = 'gs.sort';
            } else {
                $order = 'gs.' . $order;
            }
            $order_by = $order . ' ' . $sort;
        } else {
            $order_by = 's.createtime desc';
        }*/

        $order_by = 's.createtime desc';

        $field = 's.shop_id,s.shop_name,s.createtime,s.commission_rate,s.banner_img,s.view_data,s.recommend_url';
        //dump($where);die;
        $lists = Shop::alias('s')
            ->join('shop_user su', 'su.id=s.user_id')
            ->where($where)
            ->field($field)
            ->order($order_by)
            ->paginate(10, false, ['query' => request()->get()]);

        foreach ($lists as $k=>$v){
            //店铺累计营业额
            $lists[$k]['turnover'] = ShopDiscountOrder::where(['shop_id'=>$v['shop_id'],'pay_status'=>1])->sum('pay_price');

            //店铺折扣累计销售
            $lists[$k]['discount_turnover'] = ShopDiscountOrder::where(['shop_id'=>$v['shop_id'],'pay_status'=>1,'type'=>1])
                ->sum('pay_price');

            //粉丝累计创收
            $total_income = ExtendConsumeShop::alias('a')
                ->join('user_consume_log ucl','a.consume_log_id = ucl.consume_id')
                ->where(['a.shop_id'=>$v['shop_id'],'ucl.is_refund'=>0])
                ->sum('a.commission');
            $lists[$k]['total_income'] = $total_income;

            //粉丝数
            $fans_count = \app\shopapi\model\ShopFans::where(['shop_id'=>$v['shop_id']])->count();
            $lists[$k]['fans_count'] = $fans_count;
        }

        return $lists;
    }

    //商户列表
    public function lists($params,$type)
    {
        if ($type==1){
            $where = ['audit_status'=>3];
        } else {
            $where = ['audit_status'=>30];
        }


        $keyword = $params['keyword'];

        $latitude = $params['lat'];

        $longitude = $params['lng'];

        $type = $params['type'];//type：   1折扣   2   团购

        if(!empty($keyword)){
            $where['shop_name'] = ['like',"%$keyword%"];
        }

        $category_id = $params['category_id'];

        if ($category_id){
            $where['category_id'] = ['in',\app\admin\model\shop\Category::getCategoryChildrenIds($category_id)];
        }

        if ($type==2){
            $where['line_goods_num']=['>',0];
        }

        $lists = Shop::where($where)
            ->field('shop_id,shop_name,category_id,address,lat,lng,commission_rate,work_week,banner_img,start_time,end_time,commission_rate')
            ->paginate(10, false, ['query' => request()->get()]);

        foreach ($lists as $k=>$item){
            if (!empty($longitude) && !empty($latitude)){
                if ($item[ 'lng' ] && $item[ 'lat' ]) {
                    $distance = getDistance((float) $item[ 'lng' ], (float) $item[ 'lat' ], (float) $longitude, (float) $latitude);
                    $lists[ $k ][ 'distance' ] = $distance / 1000;
                } else {
                    $lists[ $k ][ 'distance' ] = 0;
                }
            }
            $lists[ $k ]['work_week'] = $this->getWorkWeek($item['work_week']);
            $lists[ $k ][ 'discount' ] = $this->calculate_discount($item['commission_rate']);
            $goods_list = $this->getGoodsList(['shop_id'=>$item['shop_id'],'goods_state'=>1]);
            $lists[ $k ][ 'goods_list' ] = $goods_list;
        }


        return $lists;
    }


    //海报
    public function poster($page,$qrcode_param,$app_type)
    {
        $qrcode_info = $this->getQrcode($app_type, $page, $qrcode_param);

        if ($qrcode_info[ 'code' ] < 0) throw new \Exception($qrcode_info['msg']);

        $member_info = User::get($qrcode_param[ 'suid' ]);
        if (empty($member_info))throw new \Exception('未获取到会员信息');

        $shop_info = $this->getShopInfo(['shop_id'=>$qrcode_param['shop_id']]);
        if (empty($shop_info))throw new \Exception('未获取到商户信息');
        $banner_img = explode(',',$shop_info['banner_img'])[0];

        try {

            $poster = new PosterExtend(740, 1100);
            $option = [
                [
                    'action' => 'setBackground', // 背景色
                    'data' => [255, 255, 255]
                ],
                [
                    'action' => 'imageCopy', // 写入店铺图片
                    'data' => [
                        ROOT_PATH.'public'.$banner_img,
                        5,
                        5,
                        730,
                        740,
                        10
                    ]
                ],
                [
                    'action' => 'imageCopy', // 写入二维码
                    'data' => [
                        $qrcode_info[ 'data' ][ 'path' ],
                        505,
                        880,
                        205,
                        205
                    ]
                ],
                [
                    'action' => 'imageText', // 写入店铺名称
                    'data' => [
                        $shop_info[ 'shop_name' ],
                        25,
                        [ 0, 0, 0 ],
                        40,
                        800,
                        440,
                        1,
                        true
                    ]
                ],
                [
                    'action' => 'imageText', // 写入店铺折扣
                    'data' => [
                       '全场',
                        23,
                        [ 0, 0, 0 ],
                        570,
                        800,
                        440,
                        1,
                        true
                    ]
                ],
                [
                    'action' => 'imageText', // 写入店铺折扣
                    'data' => [
                        $shop_info[ 'discount' ].'折',
                        25,
                        [ 193, 44, 31],
                        650,
                        800,
                        440,
                        1,
                        true
                    ]
                ],
                [
                    'action' => 'imageText', // 写入店铺地址
                    'data' => [
                        $shop_info[ 'address' ],
                        18,
                        [ 141, 141, 141 ],
                        40,
                        850,
                        640,
                        1
                    ]
                ],
                [
                    'action' => 'imageText', // 写入------
                    'data' => [
                        '--------------------------------------------------------------------------',
                        18,
                        [ 255, 129, 61 ],
                        40,
                        875,
                        700,
                        1
                    ]
                ],
                [
                    'action' => 'imageText', // 写入店铺地址
                    'data' => [
                        '长按右侧二维码',
                        18,
                        [ 0, 0, 0 ],
                        40,
                        950,
                        440,
                        1
                    ]
                ],
                [
                    'action' => 'imageText', // 写入店铺地址
                    'data' => [
                        '访问哇哇来购小程序',
                        18,
                        [ 0, 0, 0 ],
                        40,
                        1000,
                        440,
                        1
                    ]
                ],
                [
                    'action' => 'imageText', // 写入店铺地址
                    'data' => [
                        '海量店铺·折扣多多',
                        18,
                        [ 141, 141, 141 ],
                        40,
                        1050,
                        440,
                        1
                    ]
                ],
            ];

            $option_res = $poster->create($option);
            if (is_array($option_res)) return $option_res;

            $res = $option_res->jpeg('upload/poster/shop', 'shop' . $qrcode_param[ 'suid' ] . '_' . $app_type);

            if ($res['code']==0){
                return $res['data']['path'];
            } else {
                throw new \Exception($res['message']);
            }
            //return $res;

        }  catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 获取二维码
     * @param unknown $app_type 请求类型
     * @param unknown $page uniapp页面路径
     * @param unknown $qrcode_param 二维码携带参数
     * @param string $promotion_type 活动类型 null为无活动
     */
    private function getQrcode($app_type, $page, $qrcode_param)
    {
        $data = [
            'app_type' => $app_type,
            'type' => 'get',
            'data' => $qrcode_param,
            'page' => $page,
            'qrcode_path' => 'upload/qrcode/shop_share',
            'qrcode_name' => 'shop_share' . '_' . $qrcode_param[ 'suid' ],
        ];
        $qrcode_model = new Qrcode();

        if ($app_type=='weapp'){
            $res = $qrcode_model->createWxQrcode($data);
        } else {
            $res = $qrcode_model->createQrcode($data);
        }

        return $res;
    }

    //计算用户看到的折扣
    public function calculate_discount($commission_rate)
    {
        $discount = (100-$commission_rate+$commission_rate*0.6)/10;

        return $discount;
    }

    //计算团购返利
    public function goods_rebate($price,$commission_rate)
    {
        $rebate = $price*$commission_rate/100*0.4;

        return round($rebate,4);
    }


}